<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\logic\CartLogic;
use app\common\logic\OrderLogic;
use think\Db;

class Cart extends Api
{
    public $user_id = 0;
    public $user = [];

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function __construct()
    {
        parent::__construct();
        $this->user_id = $this->auth->id;
        $this->user = \app\common\model\User::get($this->user_id);
        $this->model = new \app\common\model\Cart();
    }

    /**
     * ajax 将商品加入购物车
     */
    public function ajaxAddCart()
    {
        $goods_id = $this->request->request("goods_id"); // 商品id
        $goods_num = $this->request->request("goods_num");// 商品数量
        $item_id = $this->request->request("item_id"); // 商品规格id
        if (empty($goods_id)) {
            $this->error('请选择要购买的商品', $goods_id);
        }
        if (empty($goods_num)) {
            $this->error('购买商品数量不能为0');
        }

        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        $cartLogic->setGoodsModel($goods_id);
        if ($item_id) {
            $cartLogic->setGoodsAttrModel($item_id);
        }

        $cartLogic->setGoodsBuyNum($goods_num);
        $result = $cartLogic->addGoodsToCart();
        if ($result['code'] == '1') {
            $this->success($result['msg']);
        } else {
            $this->error($result['msg']);
        }
    }


    /**
     *  购物车加减
     */
    public function changeNum()
    {
//        $id = $this->request->request('id/d');
        $goods_id = $this->request->request("goods_id/d"); // 商品id
        $goods_num = $this->request->request('goods_num/d');



        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        $cartLogic->setGoodsModel($goods_id);
        $cartLogic->setGoodsBuyNum($goods_num);
        $userCartGoods = \app\common\model\Cart::get(['user_id'=>$this->user_id,'goods_id'=>$goods_id]);
        if($userCartGoods){
            $result = $cartLogic->changeNum($userCartGoods['id'], $goods_num);
        }else{
            $result = $cartLogic->addGoodsToCart();
        }

        if ($result['code'] == 1) {
            $this->success($result['msg']);
        } else {
            $this->error($result['msg']);
        }
    }

    /**
     * 更新购物车，并返回计算结果
     */
    public function AsyncUpdateCart()
    {
        $cart = input('cart');
//        dump($cart);exit;
        $cartarr = json_decode($cart, true);
        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        $result = $cartLogic->AsyncUpdateCart($cartarr);
        return json($result);

    }

    /**
     * 查看
     */
    public function index()
    {

        $this->dataLimit = true;
        list($where, $sort, $order, $offset, $limit, $field) = $this->buildparams();

        $total = $this->model
            ->with('goods')
            ->where($where)
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->with('goods')
            ->field($field)
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        $goodsAttrM = new \app\common\model\GoodsAttr();

        $totalPrice = 0;
        $totalNum = 0;
        foreach ($list as $k => $v) {
            //规格
            $goodsAttr = $goodsAttrM->get($v['item_id']);
            if ($goodsAttr) {
                $attrName = $goodsAttr->attr['name'];

                $list[$k]['goods_attr'] = [
                    'id' => $goodsAttr['id'],
                    'attr_name' => $attrName,
                    'attr_value' => $goodsAttr['attr_value']
                ];
            }

            //计算价格
            $totalPrice += $v['goods_price']*$v['goods_num'];
            $totalNum += $v['goods_num'];

        }

        $result = array("total" => $total, "rows" => $list,'totalPrice' => $totalPrice,'totalNum' => $totalNum);


        $this->success('', $result);
    }

    /**
     * 购物车第二步确定页面,下单页面
     */
    public function order()
    {

        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        if ($cartLogic->getUserCartOrderCount() == 0) {
            $this->error('你的购物车没有选中商品', 'Cart/index');
        }
        $cartList = $cartLogic->getCartList(1); // 获取用户选中的购物车商品
//        $cartGoodsTotalNum = array_sum(array_map(function($val){return $val['goods_num'];}, $cartList));//购物车购买的商品总数
        $cartGoodsTotalFee = $cartLogic->getCartPriceInfo($cartList);
        $this->success('', ['cartGoods' => $cartGoodsTotalFee, 'cartList' => $cartList]);

    }


    /**
     * 购买方式
     */
    public function selectType()
    {
        $type = \app\common\model\Goods::getType();
        $this->success('', $type);
    }


    /**
     * 提交订单
     * @param  $cartList 购物车数据
     * @param int $address_id 地址
     * @param int $type 购买类型 订单类型:0=自己买,1=送一人,2=群发多人抢
     * @param integral_goodsids 使用积分的商品id,例1,2,3
     */
    public function addOrder()
    {
//        $cartList = $this->request->request('cartList');
        $address_id = $this->request->request('address_id', 0);
        $type = $this->request->request('type', 0);
        $integral_goodsids = $this->request->request('integral_goodsids');
        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        if ($cartLogic->getUserCartOrderCount() == 0) {
            $this->error('你的购物车没有选中商品', 'Cart/index');
        }
        $cartList = $cartLogic->getCartList(1); // 获取用户选中的购物车商品

        $integral_goodsids_arr = explode(',', $integral_goodsids);

        $orderM = new \app\common\model\Order();
        $params = [];
        $master_order_sn = $orderM->order_number();
        foreach ($cartList as $k => $v) {

            $params['user_id'] = $this->auth->id;
            $params['type'] = $type;
            $params['address_id'] = $address_id;
            $params['item_id'] = $v['item_id'];
            $params['goods_id'] = $v['goods_id'];
            $params['num'] = $v['goods_num'];
            $params['order_prom_type'] = 0;
            $params['order_prom_id'] = 0;
            $params['user_prom_id'] = 0;

            if (in_array($v['goods_id'], $integral_goodsids_arr)) {
                //使用积分的商品
                $params['integral'] = $v['goods']['exchange_integral'];
            }else{
                $params['integral'] = 0;
            }
            //下单
            $res = $orderM->addOrder($params, $master_order_sn);

            if ($res['code'] == 0) {
                $this->error($res['msg']);
            }else{
                //下单成功,清空购物车
                $cart = $this->model->get($v['id']);
                $cart->delete();
            }
        }


        $openid = Db::name('user')->where('id', $this->auth->id)->value('openid');
        $data = [
            'type' => $res['data']['type'],
            'order_sn' => $res['data']['master_order_sn'],
            'total_amount' => $res['data']['total_amount'],
            'openid' => $openid

        ];

        $this->success('', $data);
    }

    public function orderPrice()
    {
        $cart_ids = $this->request->request('cart_ids');
        $cart_ids = json_decode($cart_ids, true);


        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        $cartList = $cartLogic->getCartList(1); // 获取用户选中的购物车商品



        $total_integral_fee = 0;
        foreach ($cartList as $k => $v) {
            if (in_array($v['id'], $cart_ids)) {
                //使用积分的商品
                $total_integral_fee += intval($v['goods']['exchange_integral']*$v['goods_num']);

            }
        }


        $cartPriceInfo = $cartLogic->getCartPriceInfo($cartList);
        $new = ($cartPriceInfo['total_fee'] * 100 - $total_integral_fee * 100) / 100;
        $this->success('', number_format($new, 2, '.', ''));


    }


}